#include "ImageFeature.h"
#include "../Scene/ZDataManager.h"
#include "../Tools/ConfigManager.h"
#include <fstream>

GLOBAL_NAMESPACE_BEGIN
NAMESPACE_MACHINE_LEARNING_BEGIN

static const char* imageFeatureNamePrefix__ = "ImageFeaturePrefix";

static std::string generateName(ImageSpace::Image* ima)
{
    std::string prefix;
    prefix = ConfigManager::getSingletonPtr()->getConfig()->read(imageFeatureNamePrefix__, prefix);
    std::string name(ima->getName());
    std::string ret(prefix + name);
    return ret.substr(0, ret.find_last_not_of(".")+1);
}

ImageFeature::ImageFeature(ImageSpace::Image* ima)
    : ima_(ima)
{
    setName(generateName(ima));
}

ImageFeature::ImageFeature(const std::string& fullName)
{
    //loadFeatureFromFile(fullName.c_str());
    setName(fullName.substr(fullName.find_last_of("/\\")+1));
    setFullPath(fullName);
}

void ImageFeature::setFeatureVector(const std::vector<double>& feature)
{
    feature_ = feature;
}

void ImageFeature::setLabelVector(const std::vector<int>& label)
{
    label_ = label;
    std::sort(label_.begin(), label_.end());
}

ImageSpace::Image* ImageFeature::getImage()
{
    return ima_;
}

std::vector<double> ImageFeature::getFeatureVector()
{
    return feature_;
}

std::vector<int> ImageFeature::getLabelVector()
{
    return label_;
}

int ImageFeature::getFeatureDim()
{
    return feature_.size();
}

void ImageFeature::setImage(ImageSpace::Image* ima, bool bGenerateName)
{
    ima_ = ima;
    if (bGenerateName)
        setName(generateName(ima));
}

bool ImageFeature::loadFeatureFromFile(const char* fileName)
{
    std::ifstream fin(fileName);
    if (!fin)
        return false;

    feature_.clear();
    int nSize = 0;
    double oneF;
    fin >> nSize;
    for (int i = 0; i < nSize; i++)
    {
        fin >> oneF;
        feature_.push_back(oneF);
    }

    fin.close();
    return true;
}

bool ImageFeature::saveFeatureToFile(const char* fileName)
{
    std::ofstream fout(fileName);
    if (!fout)
        return false;

    fout << feature_.size() << "\n";
    for (int i = 0; i < feature_.size(); i++)
    {
        fout << feature_.at(i) << " ";
    }
    fout << "\n";

    fout.close();
    return true;
}

void ImageFeature::addFeatureImage(const cv::Mat& featureImg)
{
    featureImages_.push_back(featureImg);
}

cv::Mat ImageFeature::getFeatureImage(int idx)
{
    return featureImages_.at(idx);
}

void ImageFeature::setFullPath(const std::string& path)
{
    saveFileFullPath_ = path;
}

std::string ImageFeature::getFullPath()
{
    return saveFileFullPath_;
}

void ImageFeature::setName(const std::string& name)
{
    name_ = name;
}

std::string ImageFeature::getName()
{
    return name_;
}

NAMESPACE_MACHINE_LEARNING_END
GLOBAL_NAMESPACE_END
